<!--页面组件-->
<template>
  <div>
    <CCard class="cdHead addTask">
      <div style="display: flex">
        <CCol sm="12" class="showContentRight">
          <CSelect
            label="任务类型"
            placeholder="请选择"
            :options="taskTypeList"
            :value.sync="pushTaskType"
            @change="pushTaskTypeChange($event)"
            horizontal
            class="input"
          />
          <CInput
            label="任务名称"
            v-model="upData.taskName"
            placeholder="请输入任务名称"
            horizontal
            class="input"
          />
          <CSelect
            label="扫描间隔"
            placeholder="请选择"
            :options="cronList"
            :value.sync="upData.crontabExpress"
            horizontal
            class="input"
          />
          <div style="display: flex">
            <CInput
              label="扫描目录"
              v-model="upDataTaskParam.scanDir"
              placeholder="请输入扫描目录"
              horizontal
              class="input"
            />
            <CButton
              color="info"
              size="sm"
              @click="selectPushTaskScanDir('scanDir')"
              class="btnSelect system-btn-style"
              >...</CButton
            >
          </div>
          <div style="display: flex">
            <CInput
              label="生产目录"
              v-model="upDataTaskParam.proDir"
              placeholder="请输入生产目录"
              horizontal
              class="input"
            />
            <CButton
              color="info"
              size="sm"
              @click="selectPushTaskProDir('proDir')"
              class="btnSelect system-btn-style"
              >...</CButton
            >
          </div>
          <!-- <CSelect
            label="组织机构"
            placeholder="请选择"
            :options="enterpriseList"
            :value.sync="upDataTaskParam.enterId"
            @change="selectEnterprise($event)"
            horizontal
            class="input"
          /> -->
          <!-- <CSelect
            label="用户部门"
            horizontal
            :value.sync="upDataTaskParam.orgId"
            :options="organizationList"
            placeholder="请选择"
            @change="selectOrganization($event)"
            class="input"
          />
          <CSelect
            label="用户名"
            horizontal
            :value.sync="upDataTaskParam.userId"
            :options="userNameList"
            placeholder="请选择"
            @change="selectUserName($event)"
            class="input"
          /> -->
          <!-- <CSelect
            label="文件类型"
            horizontal
            :options="fileTypeList"
            :value.sync="upDataTaskParam.finishFlag"
            placeholder="请选择文件类型"
            @change="selectFileType($event)"
            class="input"
          /> -->
          <CInput
            label="用户部门"
            v-model="upDataTaskParam.department"
            placeholder="请输入用户部门"
            horizontal
            class="input"
          />
          <CInput
            label="用户名"
            v-model="upDataTaskParam.taskOwner"
            placeholder="请输入用户部门"
            horizontal
            class="input"
          />
          <CInput
            label="匹配后缀"
            v-model="upDataTaskParam.finishFlag"
            placeholder="后缀必须包含点（例如：.tif）"
            horizontal
            class="input"
          />
          <label class="label" style="padding-right: 15px">流程</label>

          <Select
            filterable
            transfer
            :value="parseInt(upData.flowId)"
            @on-select="processingOnChange"
            style="width: 61%; margin-left: -25px"
          >
            <Option
              v-for="item in processingList"
              :value="item.id"
              :key="item.id"
              >{{
                item.workflowName + "-" + item.workflowVersion + ".0"
              }}</Option
            >
          </Select>
          <div class="select-rou" style="margin-top: 3px;display: flex">
            <label class="label" style="margin-right: 7px;padding-top: 7px" >规则</label>
            <div style="display: flex">
              <Select
                      filterable
                      transfer
                      v-model="upDataTaskParam.selectData"
                      style="width: 71px;height: 35px;"
              >
                <Option
                        v-for="item in selectRow"
                        :value="item.value"
                        :key="item.value">{{item.label }}</Option>
              </Select>

              <CInput
                      v-model="upDataTaskParam.regexExpressData"
                      horizontal
                      style="width: 211px;margin-right: 4px"
                      :placeholder="upDataTaskParam.selectData=='ABC'?'以^开头,以$结尾':'请输入内容'"
                      class="input"
              />
            </div>
          </div>
        </CCol>

        <CCol md="12" class="showContentRight">
          <CForm>
            <ul>
              <li v-for="(item, index) in showParamList" :key="index">
                <CSelect
                  :label="item.dictName"
                  :options="flowParamList"
                  :value.sync="item.bindingFlowKey"
                  placeholder="请选择"
                  horizontal
                ></CSelect>
              </li>
            </ul>
          </CForm>
        </CCol>
      </div>
    </CCard>

    <Modal
      v-model="showPushTaskZtreeModal"
      draggable
      scrollable
      title="推送任务选择目录"
      id="my-modal"
    >
      <!-- :styles="modalStyle" -->
      <p slot="header" class="modalHeader" sty>选择目录</p>
      <CButtonClose slot="close" @click="pushTaskMenuCancel" />
      <div class="treeDiv">
        <ul id="pushTaskTree2" class="ztree"></ul>
      </div>

      <template #footer>
        <CButton @click="pushTaskMenuCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="pushTaskMenuOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <!-- <CModal
      title="推送任务选择目录"
      color="info"
      :show.sync="showPushTaskZtreeModal"
      :closeOnBackdrop="false"
      size="lg"
      centered
    >
      <div class="treeDiv">
        <ul id="pushTaskTree" class="ztree"></ul>
      </div>

      <template #header>
        <h5>选择目录</h5>
        <CButtonClose @click="pushTaskMenuCancel" />
      </template>
      <template #footer>
        <CButton @click="pushTaskMenuOk" color="info">确定</CButton>
        <CButton @click="pushTaskMenuCancel" color="light">取消</CButton>
      </template>
    </CModal> -->
  </div>
</template>
<script>
export default {
  name: "updateTask",
  data() {
    return {
      // modalStyle: { top: "250px" },
      showParamList: [],

      flowParamList: [],
      processingList: [],
      id: -1,
      sensor: "",
      cronList: [],
      pushTaskType: 2, //1 紧急 2、常规
      bIsScanDir: true,
      taskTypeList: [],

      items: [],
      upData: {
        flowName: "",
        crontabExpress: "",
        flowId: "",
        sourceId: 2, //常规
        taskName: "",
        taskParameter: "",
      },
      selectRow: [
        {label:"文件开头",value:"^ABC.*$"},
        {label:"文件结尾",value:"^.*ABC$"},
        {label:"文件包含",value:"^.*ABC.*$"},
        {label:"文件不包含",value:"^((?!ABC).)*$"},

        /*    {label:"不包含ABC",value:"^((?!ABC).)*str((?!ABC).)*$"},*/
        {label:"自定义",value:"ABC"},
      ],
      upDataTaskParam: {
        selectData: "",
        regexExpressData: "",
        regexExpress: "",
        scanDir: "",
        proDir: "",
        finishFlag: "",
        taskOwner: "", //任务发起者
        department: "", //发起者部门
        // enterId: -1, //组织机构
        // orgId: -1, //部门
        // userId: -1, //用户
      },
      // fileTypeList: [".gz", ".zip"],
      // enterpriseList: [],
      organizationList: [],
      userNameList: [],
      showPushTaskZtreeModal: false,
      haveHeader: false,
    };
  },
  watch: {},
  mounted() {
    debugger
    this.getCronList();
    
    // this.getEnterpriseList();
  },

  methods: {
    getFlowKey() {
      let objFlowKeyList = {};
      this.showParamList.forEach((ele) => {
        objFlowKeyList[ele.dictCode] = ele.bindingFlowKey;
        this.upData.flowKey = objFlowKeyList;
      });
    },
    getParamByDictCode() {
      let _this = this;
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "flowKey",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          let dataList = res.data.data.dictCodeList;

          let flowKey = JSON.parse(_this.upData.flowKey);
          //用于界面字典值回显绑定的值
          for (let key in flowKey) {
            for (let i = 0; i < dataList.length; i++) {
              if (dataList[i].dictCode === key) {
                dataList[i].bindingFlowKey = flowKey[key];
                // _this.$set(dataList[i], "bindingFlowKey", flowKey[key]);
                continue;
              }
            }
          }
          _this.showParamList = dataList;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    getTaskTypeByDictCode() {
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "timingTask",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0 && res.data.success) {
          let dictCodeList = res.data.data.dictCodeList;
          for (let dictCode of dictCodeList) {
            let obj = {
              label: dictCode.dictName,
              value: parseInt(dictCode.dictCode),
            };
            this.taskTypeList.push(obj);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    processingOnChange(item) {
      this.upData.flowId = item.value;
      // let index = item.label.lastIndexOf("-");

      this.upData.flowName = item.label; // item.label.substring(0, item.label.length - index);
      this.getflowParamsByFlowId(item.value);
    },
    getflowParamsByFlowId(flowId) {
      let path = this.$api.processingApi.getParam;
      let param = {
        workFlowId: flowId,
      };
      this.flowParamList = [];
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0) {
          let globalParam = JSON.parse(res.data.data.processParameters)
            .globalParam;
          let inputParam = JSON.parse(res.data.data.processParameters)
            .inputParam;

          for (let gParam of globalParam) {
            let label = "基本参数" + " - " + gParam.label;
            let globalFlowParam = {
              label: label,
              value: gParam.workflowInputKey,
            };
            this.flowParamList.push(globalFlowParam);
          }

          for (let paramFlow of inputParam) {
            for (let paramAlgo of paramFlow) {
              let label = paramAlgo.groupName + " - " + paramAlgo.label;
              let flowParam = {
                label: label,
                value: paramAlgo.workflowInputKey,
              };
              this.flowParamList.push(flowParam);
            }
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    selectFileType(event) {
      this.upDataTaskParam.finishFlag = event.target.value;
    },

    pushTaskTypeChange(event) {
      this.pushTaskType = parseInt(event.target.value);
      this.upData.sourceId = this.pushTaskType;
    },
    // 应急推送任务扫描目录选择
    selectPushTaskScanDir(type) {
      this.bIsScanDir = true;
      this.showPushTaskZtreeModal = true;
      this.pushTaskMenu(type);
    },
    // 应急推送任务生产目录选择
    selectPushTaskProDir(type) {
      this.bIsScanDir = false;
      this.showPushTaskZtreeModal = true;
      this.pushTaskMenu(type);
    },
    pushTaskMenu(type) {
      let treeObj = $.fn.zTree.getZTreeObj("pushTaskTree2");
      if (treeObj != null) {
        var nodes = treeObj.getNodes();
        for (var i = nodes.length - 1; i >= 0; i--) {
          treeObj.removeNode(nodes[i]);
        }
      }

      let path; //1为共享文件夹,2为用户文件夹,3为紧急推送扫描文件夹,4为应急任务生产根目录,5为常规推送生产根目录,6为自动推送Modis生产根目录,7为自动推送Modis扫描根目录
      if (type == "scanDir") {
        if (this.pushTaskType == 1) {
          path = this.$api.processingApi.fileRootPath + 3;
        } else if (this.pushTaskType == 2) {
          path = this.$api.processingApi.fileRootPath + 5;
        } else if (this.pushTaskType === "ModisTask") {
          path = this.$api.processingApi.fileRootPath + 7;
        } else {
          path = this.$api.processingApi.fileRootPath + 1;
        }
      } else {
        if (this.pushTaskType == 1) {
          path = this.$api.processingApi.fileRootPath + 4;
        } else if (this.pushTaskType == 2) {
          path = this.$api.processingApi.fileRootPath + 5;
        } else if (this.pushTaskType === "ModisTask") {
          path = this.$api.processingApi.fileRootPath + 6;
        } else {
          path = this.$api.processingApi.fileRootPath + 1;
        }
      }
      this.pushTaskMenuSetting(path);
    },
    // 应急推送任务扫描目录、生产目录Ztree设置
    pushTaskMenuSetting(urlPath) {
      let checkType = { Y: "", N: "" }; //父与子的关联去掉
      let setting = {
        check: {
          enable: true,
          nocheckInherit: false,
          chkboxType: checkType,
        },
        data: {
          simpleData: {
            enable: true,
          },
        },
        callback: {
          beforeClick: this.beforeClick,
          onClick: this.zTreeOnClick,
          onCheck: this.zTreePushTaskOnCheck,
          onExpand: this.zTreeOnClick,
        },
      };

      this.http.get(urlPath).then((res) => {
        let data = res.data;
        if (data.success == true) {
          $.fn.zTree.init($("#pushTaskTree2"), setting, data.data);
        }
      });
    },
    zTreePushTaskOnCheck(event, treeId, treeNode) {
      var treeObj = $.fn.zTree.getZTreeObj(treeId),
        nodes = treeObj.getCheckedNodes(true);

      if (!treeNode.isParent) {
        this.$Message.warning("请选择文件夹！");
        treeNode.checked = false;
        treeObj.updateNode(treeNode);
        return;
      }
      if (!this.bIsScanDir && nodes.length > 1) {
        //限制单个文件夹
        this.$Message.warning("生产目录只能选择一个文件夹！");
        treeNode.checked = false;
        treeObj.updateNode(treeNode);
        return;
      }
    },
    pushTaskMenuOk() {
      let treeObj = $.fn.zTree.getZTreeObj("pushTaskTree2"),
        nodes = treeObj.getCheckedNodes(true);
      let tempNode = "";
      let info = "";
      for (var index in nodes) {
        tempNode = nodes[index];
        if (info == "") {
          info = tempNode.id;
        } else {
          info += ";" + tempNode.id;
        }
      }

      if (this.bIsScanDir) {
        this.upDataTaskParam.scanDir = info;
      } else {
        this.upDataTaskParam.proDir = info;
      }

      this.pushTaskReset();
    },
    pushTaskMenuCancel() {
      this.pushTaskReset();
    },
    pushTaskReset() {
      var treeObj;
      this.showPushTaskZtreeModal = false;
      treeObj = $.fn.zTree.getZTreeObj("pushTaskTree2");
      if (treeObj == null) return;

      var nodes = treeObj.getNodes();
      for (var i = nodes.length - 1; i >= 0; i--) {
        treeObj.removeNode(nodes[i]);
      }
    },
    reset() {
      this.taskTypeList = [];
    },
    zTreeOnClick(event, treeId, treeNode) {
      let path = this.$api.processingApi.getFileListByPath;
      let param = {
        path: treeNode.id,
      };
      var treeObj = $.fn.zTree.getZTreeObj(treeId);
      var node = treeObj.getNodeByParam("id", treeNode.id);
      treeObj.selectNode(node);
      let sNode = treeObj.getSelectedNodes();
      if (sNode.length > 0) {
        let zAsync = sNode[0].zAsync;
        treeObj.reAsyncChildNodes(treeNode, "refresh");
        if (zAsync) {
        } else {
          this.http.get(path, param).then((res) => {
            let data = res.data;
            if (data.success == true) {
              treeNode.halfCheck = false;
              treeObj.addNodes(treeNode, data.data, false);
              sNode[0].zAsync = true;
            }
          });
        }
      }
    },

    getProcessingData() {
      let that = this;
      let path = this.$api.processingApi.search;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          that.processingList = res.data.data;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    getAuto(id) {
      let self = this;
      let path = this.$api.processingApi.autoTaskQuery + "/" + id;
      this.http.get(path).then((res) => {
        self.loading = false;
        if (res.data.code == 0) {
          self.upData = res.data.data;
          self.pushTaskType = self.upData.sourceId;
          self.getTaskTypeByDictCode();
          self.getProcessingData();
          self.getflowParamsByFlowId(self.upData.flowId);
          self.getParamByDictCode();
          if (self.upData.taskParameter) {
            self.upDataTaskParam = JSON.parse(self.upData.taskParameter);
            // self.upDataTaskParam.enterId = parseInt(
            //   self.upDataTaskParam.enterId
            // );
            // self.upDataTaskParam.orgId = parseInt(self.upDataTaskParam.orgId);
            // self.upDataTaskParam.userId = parseInt(self.upDataTaskParam.userId);

            // self.getOrganizationList(self.curEnterId);
            // self.getUserNameList(self.curOrgId);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    //被父组件调用
    save(updId) {
      let self = this;
      this.getFlowKey();
      let path = this.$api.processingApi.update + "/" + updId;
      //处理匹配后缀的格式是否包含.
      // let suffix = self.upDataTaskParam.finishFlag;
      // if (suffix.indexOf(".") !== 0) {
      //   self.upDataTaskParam.finishFlag = "." + suffix;
      // }

      this.upDataTaskParam.regexExpress =this.upDataTaskParam.regexExpressData? this.upDataTaskParam.selectData.replace("ABC", this.upDataTaskParam.regexExpressData):"";
      self.upData.taskParameter = JSON.stringify(self.upDataTaskParam);

      let param = {
        crontabExpress: self.upData.crontabExpress,
        flowId: self.upData.flowId,
        flowName: self.upData.flowName,
        sourceId: self.upData.sourceId,
        taskName: self.upData.taskName,
        status: 0,
        flowKey: JSON.stringify(this.upData.flowKey),
        taskParameter: this.upData.taskParameter,
      };
      this.http.post(path, param).then((res) => {
        if (res.data.success) {
          this.$emit("closeupdateTask", false);
          this.$Message.success("更新成功");
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    getCronList() {
      let path = this.$api.processingApi.getAllChildByDictCode;
      let param = {
        dictCode: "cron",
      };
      this.http.get(path, param).then((res) => {
        if (res.data.code == 0) {
          let dictCodeList = res.data.data.dictCodeList;
          this.cronList.push({ label: "请选择", value: "" });
          for (let dictCode of dictCodeList) {
            let cron = {
              label: dictCode.dictName,
              value: dictCode.dictCode,
            };
            this.cronList.push(cron);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    // getEnterpriseList() {
    //   let self = this;
    //   self.enterpriseList = [];
    //   let path = self.$api.processingApi.getTree;
    //   let param = {
    //     isTree: false,
    //   };
    //   this.http.get(path, param).then((res) => {
    //     if (res.data.success) {
    //       let content = res.data.data;
    //       for (let i = 0; i < content.length; i++) {
    //         let enterprise = {
    //           value: content[i].id,
    //           label: content[i].name,
    //         };
    //         self.enterpriseList.push(enterprise);
    //       }
    //     } else {
    //       this.$Message.error(res.data.message);
    //     }
    //   });
    // },
    // selectEnterprise($event) {
    //   let self = this;
    //   self.upDataTaskParam.enterId = paeseInt(event.target.value);
    //   self.getOrganizationList(self.upDataTaskParam.enterId);
    // },
    // getOrganizationList(enterpriseId) {
    //   let self = this;

    //   self.organizationList = [];
    //   let path = this.$api.processingApi.organization;
    //   let param = {
    //     enterId: enterpriseId,
    //     isTree: false,
    //   };

    //   this.http.get(path, param).then((res) => {
    //     if (res.data.success) {
    //       let content = res.data.data;

    //       for (let i = 0; i < content.length; i++) {
    //         let organization = {
    //           value: content[i].id,
    //           label: content[i].name,
    //         };
    //         self.organizationList.push(organization);
    //       }
    //     } else {
    //       this.$Message.error(res.data.message);
    //     }
    //   });
    // },
    // selectOrganization($event) {
    //   let self = this;

    //   let selectedIndex = event.target.options.selectedIndex;
    //   let organizationName = event.target.options[selectedIndex].label;

    //   self.upDataTaskParam.orgId = parseInt(event.target.value);
    //   self.upDataTaskParam.department = organizationName;
    //   self.getUserNameList(self.upDataTaskParam.orgId);
    // },
    // getUserNameList(organizationId) {
    //   let self = this;
    //   self.userNameList = [];
    //   let path = self.$api.processingApi.queryAllUser;
    //   let param = {
    //     Authorization: window.sessionStorage.getItem("PIECloud-Token"),
    //     organizationId: organizationId,
    //   };

    //   this.http.get(path, param).then((res) => {
    //     if (res.data.success) {
    //       let content = res.data.data;

    //       for (let i = 0; i < content.userList.length; i++) {
    //         let userName = {
    //           value: content.userList[i].id,
    //           label: content.userList[i].username,
    //         };
    //         self.userNameList.push(userName);
    //       }
    //     } else {
    //       this.$Message.error(res.data.message);
    //     }
    //   });
    // },
    // selectUserName($event) {
    //   let self = this;

    //   let selectedIndex = event.target.options.selectedIndex;
    //   let userName = event.target.options[selectedIndex].label;

    //   self.upDataTaskParam.userId = parseInt(event.target.value);
    //   self.upDataTaskParam.taskOwner = userName;
    // },
  },
};
</script>
<style scoped>
.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.76563rem;
  line-height: 1.5;
  border-radius: 0.2rem;
  width: 50px;
}
.label {
  width: 80px;
  margin-right: 20px;
  text-align: right;
}

.input {
  width: 300px;
  cursor: pointer;
}
</style>
<style lang='scss' scoped>
.treeDiv {
  height: 500px;
  // width: 760px;
  width: 504px;
  overflow-y: auto;
}
.btnSelect {
  width: 30px;
  height: 26px;
  margin-left: 10px;
  margin-top: 5px;
}
.card-header {
  height: 60px;
  padding: 0px;
  padding-top: 23px;
  padding-left: 23px;
}

::-webkit-scrollbar-thumb {
  background-color: #7eb8ee;
}

.cdHead {
  height: 60vh !important;
  border: none;
}
.form-group {
  margin-bottom: 0.5rem;
}
.showContentRight {
  max-width: 50%;
  height: 466px;
  overflow-x: hidden;
  overflow-y: auto;
}
ul {
  list-style: none;
}
</style>
